<template>
    <div class="weChat_main">
        <div class="bindWeChat" v-if="!isWeChat" key="1">
            <h2 class="title">微信扫码绑定</h2>
            <div class="WeChat">
                <!-- <img src=""> -->
                <div id="login_container"
                    style="height: 100%; width: 100%;display: flex;justify-content: center;align-items: center;"></div>
            </div>
        </div>
        <div class="dialog_main" v-else key="2">
            <h2 class="title">解除绑定</h2>
            <div class="from_title">为确认是您本人操作，请完成以下验证</div>
            <el-form ref="forgotForm" :model="sizeForm" size="mini" :rules="changeRiles" label-width="135px"
                label-position="left">
                <el-form-item label="已绑定的手机">
                    <div class="phone">{{ showPhone }}</div>
                </el-form-item>
                <el-form-item prop="validCode" label="短信验证码">
                    <el-tooltip class="item" effect="dark" content="请输入验证码" placement="right-end"
                        popper-class="popperClass">
                        <el-input v-model.trim="sizeForm.validCode" placeholder="请输入验证码" style="width: 45%;" />
                    </el-tooltip>
                    <el-button class="verify-btn" size="medium" @click="sendValidation">{{ validation }}</el-button>
                </el-form-item>
                <el-button type="primary" class="primary" @click="clickforgot">解除绑定</el-button>
            </el-form>
        </div>
    </div>
</template>

<script>
import { getWeChatConfigRequest } from '@/api/login'
import { bindingWeChatRequest, unbindingWeChatRequest, getVerificationCodeRequest } from '@/api/user'
export default {
    name: 'GenescloudUiChangeWeChat',
    props: {
        isWeChat: {
            type: Boolean,
            default: false
        },
        bindingPhone: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            //微信二维码配置
            wxConfig: null,
            sizeForm: {
                validCode: '',
            },
            timer: null,
            validation: '发送验证码',
            countdown: 60,
            bindPhone: this.bindingPhone,
            changeRiles: {
                validCode: [
                    { required: true, message: '请输入验证码', trigger: 'blur' },
                    { pattern: /^[0-9]{6}$/, message: '请输入6位验证码', trigger: ['change', 'blur'] }
                ],
            }
        };
    },
    computed: {
        showPhone() {
            let left = this.bindPhone.substring(0, 3)
            let right = this.bindPhone.substring(this.bindPhone.length - 3)
            return left + '****' + right
        },
    },

    async mounted() {
        if (!this.isWeChat) {
            window.addEventListener('message', async (msg) => {
                if (msg.data.code && msg.data.state) {
                        const res = await bindingWeChatRequest(msg.data)
                        if (res.code !== 200) {
                            this.$message.error('操作失败,请刷新页面重新操作！')
                            // console.log('操作失败,请刷新页面重新操作！');
                        } else {
                            this.clear()
                            this.$emit('complete', 'weChat')
                        }
                }
            })
            const res = await getWeChatConfigRequest()
            if (res.code !== 200) return this.$message.error('系统异常，请联系管理员！')
            this.wxConfig = res.data
            this.wxLogin()
        }
    },

    methods: {
        wxLogin() {
            this.$nextTick(() => {
                // console.log(3);
                //css内容
                const { appid, redirectUri } = this.wxConfig
                var content = ".impowerBox .qrcode {width: 300px;border:0} .impowerBox .title {display: none;} .impowerBox .info {width: 200px;display: none;} .status_icon {display: none}";
                //记住一定要注明文件类型是css
                var blob = new Blob([content], { type: "text/css;charset=utf-8" });
                var reader = new FileReader();
                const herf = redirectUri + '/login_code'
                reader.readAsDataURL(blob);
                reader.onload = function (e) {
                    var wxqrcode = new WxLogin({
                        self_redirect: true, //true将页面跳转放在ifream里面   false直接跳转到要跳转的页面
                        id: "login_container",
                        appid: appid,
                        scope: "snsapi_login",
                        redirect_uri: encodeURIComponent(herf),
                        href: this.result,//data:text/css;charset=utf-8;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDIwMHB4O30uaW1wb3dlckJveCAudGl0bGUge2Rpc3BsYXk6IG5vbmU7fS5pbXBvd2VyQm94IC5pbmZvIHt3aWR0aDogMjAwcHg7fQ==
                        state: Math.ceil(Math.random() * 1000),//为了防止csrf（跨站请求伪造攻击），设置一个3位的随机数
                        style: "black",
                    });
                };
            });
        },
        clear() {
            clearInterval(this.timer);
            this.timer = null
            this.sizeForm.validCode = ''
        },
        //验证码校验
        async sendValidation() {
            if (!this.timer) {
                try {
                    const res = await getVerificationCodeRequest({
                        mobilePhone: this.bindingPhone,
                        validCodeTypeName: 'phone_unbind_weixin'
                    })
                    if (res.code !== 200) return this.$message({
                        message: res.message,
                        type: 'warning'
                    });
                    this.validation = `60s后重新发送`;
                    this.timer = setInterval(() => {
                        if (this.countdown > 0 && this.countdown <= 60) {
                            this.countdown--;
                            if (this.countdown !== 0) {
                                this.validation = `${this.countdown}s后重新发送`;
                            } else {
                                clearInterval(this.timer);
                                this.validation = "重新发送";
                                this.countdown = 60;
                                this.timer = null;
                                this.codeDisabled = false;
                            }
                        }
                    }, 1000)
                } catch (error) {
                    this.$message.error('系统错误，请联系管理员！')
                }

            }
        },
        async clickforgot() {
            try {
                const res = await unbindingWeChatRequest({
                    mobilePhone: this.bindingPhone,
                    validCode: this.sizeForm.validCode
                })
                if (res.code !== 200) return this.$message.error(res.message)
                this.clear()
                this.$emit('complete', 'weChat')
            } catch (error) {
                this.$message.error('系统错误，请联系管理员！')
            }
        }
    },
};
</script>

<style lang="scss" scoped>
.weChat_main{
    // display: flex;
    // flex-direction: column;
    // justify-content: center;
    // align-content: center;
    padding: 0 20%;
}
.title {
    text-align: center;
    margin-bottom: 0;
    transform: translateY(-30px);
}

.WeChat {
    // margin: 30px auto;
    // margin: 0 auto;
    overflow: hidden !important;
}

.dialog_main {
    padding: 15px;
    font-size: 15px;

    .from_title {
        margin-bottom: 25px;
    }

    ::v-deep .el-form-item--mini .el-form-item__label {
        font-weight: 400;

        &::before {
            content: ''
        }
    }

    ::v-deep .el-input--mini .el-input__inner {
        border-radius: 5px;
        height: 36px;
    }

    .verify-btn {
        float: right;
        margin-right: 10%;
        border-radius: 6px;
    }

    .primary {
        margin-left: 135px;
        border-radius: 5px
    }
}
</style>